package com.leetcode.No0581;

import org.junit.Test;

import java.util.Arrays;

/**
 * @program: leetcode
 * @description: 最短无序连续子数组
 * @author: wangzhihua
 * @date: 2021-08-14
 */
public class Solution02 {

	@Test
	public void test01() {
		int[] nums = new int[]{2,6,4,8,10,9,15};
		System.out.println(findUnsortedSubarray(nums));
	}

	@Test
	public void test02() {
		int[] nums = new int[]{1};
		System.out.println(findUnsortedSubarray(nums));
	}

	public int findUnsortedSubarray(int[] nums) {
		// 从左往右遍历时记录最大值
		// 从右往左遍历时记录最小值
		int flag = Integer.MIN_VALUE;
		// 记录最小子串左右边界
		int left = -1, right = -1;
		// 从左往右
		for (int i = 0; i < nums.length; ++i) {
			if (nums[i] < flag) {
				right = i;
			} else {
				flag = nums[i];
			}
		}
		// 从右往左
		for (int i = nums.length - 1; i >= 0; --i) {
			if (nums[i] > flag) {
				left = i;
			} else {
				flag = nums[i];
			}
		}
		if (left >= right) {
			return 0;
		}
		return right - left + 1;
	}

}
